package weborb.gcf;

import org.mozilla.javascript.*;
import java.io.*;

public class Game {
	/*
	 * Get a javascript file content
	 */
	private String readFileAsString(String filePath) throws java.io.IOException {
		StringBuffer fileData = new StringBuffer(1000);
		BufferedReader reader = new BufferedReader(new FileReader(filePath));
		char[] buf = new char[1024];
		int numRead=0;
		while((numRead=reader.read(buf)) != -1) {
			fileData.append(buf, 0, numRead);
		}
		reader.close();
		return fileData.toString();
	}
	/*
	 * Load a javascript directory recusrively
	 */
	private void loadFolder(Context cx,Scriptable scope,String dirName) throws Exception {
		File dir = new File(dirName);
    
		String[] children = dir.list();
		if (children == null) {
			// Either dir does not exist or is not a directory
		} else {
			for (int i=0; i<children.length; i++) {
				// Get filename of file or directory
				String filename = children[i];
				String path = dirName+File.separator+filename;
				System.out.println(path);
				File file = new File (path);
				if ( file.isDirectory() ) 
					loadFolder(cx,scope,path);
				else {
					try {
						cx.evaluateString(scope, readFileAsString(path), path, 9, null);
					} catch( Exception e ) {
						System.out.println(e);
					}
				}
			}
		}
	}
	/*
	 * call the getGameType that returns the list of games that are registered. 
	 * this function returns an array of String 
	 */
	private String[] listGameType(Context cx,Scriptable scope) {
		Object fObj = scope.get("getGameType", scope);
		if (!(fObj instanceof Function)) {
			System.out.println("getGameType is undefined or not a function.");
		} else {
			Function f = (Function)fObj;
			Object res = f.call(cx, scope, scope, null);
			String result[] = (String[]) ((NativeJavaArray)res).unwrap();

			for ( int i=0; i< result.length; i++)
				System.out.println("Have gametype --> "+result[i]);
			return result;
		}
		return null;
	}
	/*
	 * This method Create a new JS Context and compile the javascript lib in the
	 * jslib folder. Then call the listGameType function and execute the rom.
	 */
	public void newGame () {
		String s = "print(\"Hi\");";
		Context cx = Context.enter();
		try {
			cx.setLanguageVersion(Context.VERSION_1_7 );
			Scriptable scope = cx.initStandardObjects();
			loadFolder ( cx, scope, "sys" );
			loadFolder ( cx, scope, "lib" );
			loadFolder ( cx, scope, "game" );
			this.listGameType( cx, scope);
			cx.evaluateString(scope, s, "<cmd>", 9, null);
		} catch( Exception e ) {
			System.out.println(e);
            Context.exit();
        }
	}

}
